var ZYRequestClient = require("../../../../utils/zy-request");
var requestClient;
const app = getApp();
Page({
      data:{
        userId:0,
        chooseIndex:0,
        typeOptions:['使用问题','功能建议','其他'],
        files: [],
        imageUrls:[],
        formData: {
            type:"0"
        },
        rules: [
          {
              name: 'type',
              rules: {required: true, message: '请选择类型'},
          }, 
          {
              name: 'desc',
              rules: {required: true, message: '请输入问题描述'},
          }, 
          {
              name: 'contact',
              rules: {required: true,mobile:true, message: '请输入手机号'},
          }
        ],
        navbarData:{
          showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
          title: '意见反馈', //导航栏 中间的标题
          white:true
         },
         // 导航头的高度
         height: app.globalData.height * 2 + 20
      },
      onShow(){
          
      },
      onLoad(){
        requestClient = new ZYRequestClient();
        var userInfo = wx.getStorageSync('userInfo');
        this.setData({
          selectFile: this.selectFile.bind(this),
          uploadImage: this.uploadImage.bind(this),
          userId:userInfo.id
        })
      },
      formInputChange(e) {
        const {field} = e.currentTarget.dataset;
        this.setData({
            [`formData.${field}`]: e.detail.value
        })
      },
      bindOptionChange:function(e){
        const {field} = e.currentTarget.dataset;
          this.setData({
            chooseIndex: e.detail.value,
            [`formData.${field}`]: e.detail.value
          })
      },
      chooseImage: function (e) {
        var that = this;
        wx.chooseImage({
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                that.setData({
                    files: that.data.files.concat(res.tempFilePaths)
                });
            }
        })
      },
      previewImage: function(e){
          wx.previewImage({
              current: e.currentTarget.id, // 当前显示图片的http链接
              urls: this.data.files // 需要预览的图片http链接列表
          })
      },
      selectFile(files) {
          // 判断文件后缀名和大小
          var selectFile = files.tempFiles[0];
          var etds= selectFile.path.split('.');
          if(etds.length ==2){
              var etd = etds[1].toLowerCase();
            if(etd!="jpg" && etd !="png"){
                wx.showToast({
                    title: '请上传JPG或PNG！',
                  })
            } else {
                var size = selectFile.size;
                if(size > 1024*1024){
                    wx.showToast({
                        title: '请上传小于1兆的图片!',
                      })
                } else {
                    return true;
                }
            }
          } else {
            wx.showToast({
              title: '文件上传有误！',
            })
          }
          
          return false;
      },
      uploadImage(files) {
          let that = this;
          let tempFilePaths = files.tempFilePaths;
          // 文件上传的函数，返回一个promise
          return new Promise((resolve, reject) => {
            var urls = [];
            tempFilePaths.map((tempFilePath)=>{
              that.uploadFile(tempFilePath).then(imgUrl => {
                if(imgUrl){
                  let imageUrls = that.data.imageUrls;
                  imageUrls.push(imgUrl);
                  that.setData({
                    imageUrls:imageUrls
                  });
                  urls.push(imgUrl);
                  // 判断是否上传完毕
                  if(urls.length == tempFilePaths.length){
                    resolve({urls:urls});
                  }
                } else {
                  reject('上传失败！');
                }
              });
            });
          });
      },
      uploadFile(tempFilePath){
        let that = this;
        return new Promise(resolve => {
          requestClient.uploadImage(that.data.userId,tempFilePath,function(res){
            resolve(res.data)
          });
        });
      },
      uploadError(e) {
          wx.showToast({
            title: '上传失败001！',
          })
      },
      uploadSuccess(e) {
          console.log('upload success', e.detail)
      },
      submitForm(){
          let that = this;
          that.selectComponent('#form').validate((valid, errors) => {
            if (!valid) {
                const firstError = Object.keys(errors)
                if (firstError.length) {
                  that.setData({
                        error: errors[firstError[0]].message
                    })
                }
            } else {
              var feedbackData = {
                type:that.data.formData.type,
                description:that.data.formData.desc,
                contact:that.data.formData.contact,
                screenshotUrl:that.data.imageUrls.join(','),
                createUser:that.data.userId
              };
              requestClient.saveFeedback(feedbackData,function(res){
                  wx.showModal({
                    title:'反馈结果',
                    content:'感谢您的反馈，我们会及时改进，谢谢！',
                    showCancel:false,
                    success(res){
                      wx.navigateBack({
                        delta: 1,
                        success: (res) => {},
                        fail: (res) => {},
                        complete: (res) => {},
                      })
                    }
                  })
              });
            }
          })
      }
  }
)